type TodoItem = {
  id: number;
  task: string;
  isDone: boolean;
};
const initialState = {
  list: JSON.parse(localStorage.getItem('todo-list') || '[]') as TodoItem[], // 14.4 断言TodoItem与TodoFilterType,
  type: (localStorage.getItem('todo-type') || 'all') as Todotype,
};
export type Todotype = 'all' | 'active' | 'completed';
export type TodoAction =
  | { type: 'todo/delById'; payload: number }
  | { type: 'todo/updateById'; payload: number }
  | { type: 'todo/clearIdDone' }
  | { type: 'todo/selcettype'; payload: Todotype }
  // 13.1 新增Action类型
  | { type: 'todo/addTodo'; payload: string }
  | { type: 'todo/checkAll'; payload: boolean };
export default function todoReducer(
  state = initialState,
  action: TodoAction
): typeof initialState {
  switch (action.type) {
    case 'todo/delById':
      return {
        ...state,
        list: state.list.filter((item) => item.id !== action.payload),
      };
    case 'todo/updateById':
      return {
        ...state,
        list: state.list.map((item) => {
          return {
            ...item,
            isDone: item.id === action.payload ? !item.isDone : item.isDone,
          };
        }),
      };
    // 7.3 定义分支逻辑
    case 'todo/clearIdDone':
      return {
        ...state,
        list: state.list.filter((item) => !item.isDone),
      };

    case 'todo/selcettype':
      return {
        ...state,
        type: action.payload,
      };
    // 13.2 新增的reducer计算分支
    case 'todo/addTodo':
      return {
        ...state,
        list: [
          { id: Date.now(), task: action.payload, isDone: false },
          ...state.list,
        ],
      };
    case 'todo/checkAll':
      return {
        ...state,
        list: state.list.map((item) => ({ ...item, isDone: action.payload })),
      };

    default:
      break;
  }
  return state;
}
